package com.zan.framework.context.support;

import com.zan.framework.beans.BeanDefinition;
import com.zan.framework.beans.factory.support.BeanDefinitionReader;
import com.zan.framework.beans.factory.support.BeanDefinitionRegistry;
import com.zan.framework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Zan
 * @Create 2024/4/28 18:10
 * @Description : ApplicationContext接口的子实现类，用于立即加载
 * @ClassName: AbstractApplicationContext
 */
public abstract class AbstractApplicationContext implements ApplicationContext {

    // 声明解析器变量
    protected BeanDefinitionReader beanDefinitionReader;

    // 定义用来存储bean对象的容器   key存储的是bean的id值，value存储的是bean对象
    protected Map<String, Object> singletonObjects = new HashMap<String, Object>();

    // 声明存储配置文件的路径
    protected String configLocation;

    public void refresh() throws IllegalStateException, Exception {

        // 加载BeanDefinition
        beanDefinitionReader.loadBeanDefinitions(configLocation);

        // 初始化bean
        finishBeanInitialization();
    }

    // bean的初始化
    private void finishBeanInitialization() throws Exception {
        // 获取注册表对象
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        // 获取BeanDefinition对象
        String[] beanNames = registry.getBeanDefinitionNames();

        for (String beanName : beanNames) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
            // 进行bean的初始化
            getBean(beanName);
        }
    }
}
